import {computed, ref, watch} from 'vue'
import type InputProps from "@/components/input/type/InputProps.ts";
import type InputEmits from "@/components/input/type/InputEmits.ts";
import {normalizeValue} from "@/components/utils.ts";

/**
 * created by yangtong on 2025/6/16 下午11:02
 * <br />
 * 输入框核心逻辑 - 处理基础状态和显示值
 */
export function useInputCore(props: InputProps, emit: InputEmits) {
    const displayValue = ref(normalizeValue(props.modelValue))
    const focused = ref(false)
    const isComposing = ref(false)

    /**
     * 输入框size映射成px
     */
    const sizeMap = {
        tiny: "15px",
        small: "20px",
        medium: "25px",
        large: "35px"
    }

    // 标题宽度计算
    const labelWidth = computed(() => {
        return props.label ? (props.labelWidth ?? 80) : 0
    })

    // 高度计算
    const height = computed(() => {
        if (props.type === "textarea") {
            return props.height ?? "70px"
        }

        if (props.height) {
            return props.height
        }

        return sizeMap[props.pageSize!]
    })

    const normalizedModelValue = computed(() => normalizeValue(props.modelValue))

    // 监听 modelValue 变化
    watch(() => props.modelValue, (newVal) => {
        const normalizedVal = normalizeValue(newVal)

        if (focused.value) {
            displayValue.value = normalizedVal
        } else {
            // 失焦状态显示格式化后的内容
            displayValue.value = props.format && normalizedVal.length > 0
                ? props.format(normalizedVal)
                : normalizedVal
        }
    })

    return {
        displayValue,
        focused,
        isComposing,
        labelWidth,
        height,
        normalizedModelValue
    }
}